package transports

import (
	"context"
	"encoding/json"
	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/log"
	httpTransport "github.com/go-kit/kit/transport/http"
	"net/http"
	"yanwc.gokit/user_svc/service/user"
	"yanwc.gokit/user_svc/service/user/impl"
)

//密码登录请求验证体
type loginUserNameAndPasswordRequest struct {
	UserName string `json:"user_name"`
	Password string `json:"password"`
}

//登录返回结果
type loginResponse struct {
	baseResponse
	LoginName string   `json:"login_name"`
	Token     string   `json:"token"`
	NickName  string   `json:"nick_name"`
	UserName  string   `json:"user_name"`
	Avatar    string   `json:"avatar"`
	Codes     []string `json:"codes"`
}

//密码登录endpoint
func loginUserNameAndPasswordEndPoint(loginService user.LoginService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
			req := request.(loginUserNameAndPasswordRequest)
			v, err := loginService.LoginByUserNameAndPassword(req.UserName, req.Password)
			if err != nil {
			return loginResponse{baseResponse: baseResponse{Success: false, Message: err.Error(), Code: ""}}, nil
		}
			return loginResponse{
			baseResponse: baseResponse{Success: true},
			LoginName:    v.LoginName,
			NickName:     v.LoginName,
			Token:        v.Token,
			UserName:     v.UserName,
			Avatar:       v.Avatar,
			Codes:        v.Codes,
		}, nil
	}
}

//请求编码
func decodeLoginRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var request loginUserNameAndPasswordRequest
	err := json.NewDecoder(r.Body).Decode(&request)
	if err != nil {
		return nil, err
	}
	return request, nil
}

//请求解码
func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
	return json.NewEncoder(w).Encode(response)
}

//构造请求路由
func init() {
	loginSvc := impl.LoginServiceImpl{}
	loginHandler := httpTransport.NewServer(
		loginUserNameAndPasswordEndPoint(loginSvc),
		decodeLoginRequest,
		encodeResponse,
	)
	http.Handle("/login", loginHandler)
}

type loggingMiddleware struct {
	logger log.Logger
	user.LoginService
}

